package com.example.fragement;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class Diy_Fragement_1 extends Fragment {
    public static final String BUNDLE_TITLE = "bundle_title";
    private String title;
    TextView textView1;

    public static Diy_Fragement_1 newinstance(String title) {
        Diy_Fragement_1 fragement1 = new Diy_Fragement_1();
        Bundle bundle = new Bundle();
        bundle.putString(BUNDLE_TITLE, title);
        fragement1.setArguments(bundle);
        return fragement1;
    }


    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            title = getArguments().getString(BUNDLE_TITLE);
        }

    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.diy_fragement_1, container, false);
         textView1= view.findViewById(R.id.fragement1);
        TextView textView3 = view.findViewById(R.id.fragement3);
        textView1.setText(title);
        textView3.setText(title);

        textView1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (OnTitleClickLinstener != null) {
                    OnTitleClickLinstener.onFragment1Click(title);
                }
            }
        });
        return view;
    }

    public void setOnTitleClickLinstener(Diy_Fragement_1.OnTitleClickLinstener onTitleClickLinstener) {
        OnTitleClickLinstener = onTitleClickLinstener;
    }

    OnTitleClickLinstener OnTitleClickLinstener;

    //Fragment向Activity传值采用接口回调的方式
    public interface OnTitleClickLinstener {
        void onFragment1Click(String title);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessage(Integer  count){
        Toast.makeText(getContext(),"EventBus="+String.valueOf(count),Toast.LENGTH_SHORT).show();
        textView1.setText(count.toString());
    }
}
